package qmm.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import qmm.dao.FundDao;
import qmm.entity.Fund;
import qmm.entity.Goods;
import qmm.util.JdbcUtil;

public class FundDaoImpl implements FundDao {

	@Override
	public List<Fund> findByUserId(int userId) {
		List<Fund> list = new ArrayList<Fund>();
		String sql = "select * from t_fund where user_id="+userId +" order by create_time desc";
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while(rs.next()){
				int id = rs.getInt("id");
				String createTime = rs.getString("create_time");
				int type = rs.getInt("type");
				double money = rs.getDouble("money");
				double balance = rs.getDouble("balance");
				int status = rs.getInt("status");
				String vipRemark = rs.getString("vip_remark");
				String adminRemark = rs.getString("admin_remark");
				Fund fund = new Fund(id, userId, createTime, type, money, balance, status, vipRemark, adminRemark);
				list.add(fund);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int charge(int userId, double money,double balance, String vipRemark) {
		String sql = "INSERT INTO t_fund (user_id, type, money, balance, status, vip_remark) VALUES ("+userId+",  1, "+money+", "+balance+", 4, '"+vipRemark+"')";
		return JdbcUtil.update(sql);
	}

	@Override
	public int consume(int userId, double money, double balance) {
		String sql = "INSERT INTO t_fund (user_id, type, money, balance, status) VALUES ("+userId+",  2, "+money+", "+balance+", 1)";
		return JdbcUtil.update(sql);
	}

	@Override
	public double getBalance(int userId) {
		double balance = 0;
		String sql = "select balance from t_fund where user_id = "+userId+" order by create_time desc limit 1";
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
				balance = rs.getDouble(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return balance;
	}


}
